package com.hendraanggrian.appcompat.widget;

import com.hendraanggrian.appcompat.socialview.commons.ResourceTable;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.components.Image;
import ohos.agp.components.ProgressBar;
import ohos.agp.utils.TextTool;
import ohos.app.Context;

/**
 * Note that this adapter is completely optional, any adapter extending
 */
public class MentionArrayAdapter<T extends Mentionable> extends SocialArrayAdapter<T> {
    private final int defaultAvatar;

    public MentionArrayAdapter(Context context) {
        this(context, ResourceTable.Media_socialview_ic_mention_placeholder);
    }

    public MentionArrayAdapter(Context context, int defaultAvatar) {
        super(context, ResourceTable.Media_socialview_ic_mention_placeholder);
        this.defaultAvatar = defaultAvatar;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Component getComponent(int position, Component convertView, ComponentContainer parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutScatter.getInstance(getContext())
                    .parse(ResourceTable.Layout_socialview_layout_mention_ohos, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final T item = getItem(position);
        if (item != null) {
            holder.usernameView.setText((String) item.getUsername());
            final CharSequence displayname = item.getDisplayname();
            if (!TextTool.isNullOrEmpty(displayname)) {
                holder.displaynameView.setText((String) displayname);
                holder.displaynameView.setVisibility(Component.VISIBLE);
            } else {
                holder.displaynameView.setVisibility(Component.HIDE);
            }
            holder.avatarView.setPixelMap(defaultAvatar);
            holder.loadingView.setVisibility(Component.HIDE);
        }
        return convertView;
    }

    private static class ViewHolder {
        private final Image avatarView;
        private final ProgressBar loadingView;
        private final Text usernameView;
        private final Text displaynameView;

        ViewHolder(Component itemView) {
            avatarView = (Image) itemView.findComponentById(ResourceTable.Id_socialview_mention_avatar);
            loadingView = (ProgressBar) itemView.findComponentById(ResourceTable.Id_socialview_mention_loading);
            usernameView = (Text) itemView.findComponentById(ResourceTable.Id_socialview_mention_username);
            displaynameView = (Text) itemView.findComponentById(ResourceTable.Id_socialview_mention_displayname);
        }
    }
}